package com.otitan.la.forest.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.auth.framework.basepro.common.AuthCommon;
import com.otitan.la.forest.system.constant.StaticConstant;
import com.otitan.la.forest.system.exception.FileException;
import com.otitan.la.forest.system.mapper.FileInfoMapper;
import com.otitan.la.forest.system.entity.FileInfoEntity;
import com.otitan.la.forest.system.service.FileInfoService;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfoEntity> implements FileInfoService {

    @Autowired
    private AuthCommon authCommon;
    @Resource
    private FileInfoMapper fileInfoMapper;

    @Override
    public DataResult add(List<FileInfoEntity> fileList) {
        // 获取用户信息
        JSONObject user = authCommon.getLoginUserInfo();
        String realName = user.get("realName").toString();
        fileList.forEach(dto ->{
            dto.setUploadUserName(realName);
            if(dto.getIsFile().equals(StaticConstant.IS_FILE)){
                dto.setExtendName(FilenameUtils.getExtension(dto.getFileName()));
            }else{
                LambdaQueryWrapper<FileInfoEntity> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(FileInfoEntity::getFileName,dto.getFileName());
                int count=this.count(queryWrapper);
                if(count>0){
                    throw new FileException("新建文件夹重复");
                }
            }
        });
        boolean isSuccess = this.saveBatch(fileList);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    @Override
    public DataResult batchDelete(List<String> ids) {
        boolean isSuccess = this.removeByIds(ids);
        log.debug("\n>>>>>>>>> 【删除 】 <<<<<<<<<\n操作结果：{}，ids：{}\n>>>>>>>>> ---- <<<<<<<<<", isSuccess, ids);
        return DataResult.success();
    }

    @Override
    public DataResult batchDeleteByBusiId(List<String> ids) {
        LambdaQueryWrapper<FileInfoEntity> queryWrapper = Wrappers.lambdaQuery();
        if(CollUtil.isNotEmpty(ids)){
            queryWrapper.in(FileInfoEntity::getBusinessId, ids);
            this.remove(queryWrapper);
            return DataResult.success();
        }
        return DataResult.fail("ids为空，删除失败！");
    }

    @Override
    public DataResult batchDeleteById(List<String> ids) {
        if(CollUtil.isNotEmpty(ids)){
            this.removeByIds(ids);
            return DataResult.success();
        }
        return DataResult.fail("ids为空，删除失败！");
    }

    @Override
    public DataResult editor(FileInfoEntity fileInfo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        boolean isSuccess = this.updateById(fileInfo);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

//    @Override
//    public DataResult findPageData(long page, long size, FileInfoDTO fileInfo) {
//        Page pagePlug = new Page(page, size);
//        LambdaQueryWrapper<FileInfoEntity> queryWrapper = Wrappers.lambdaQuery();
//        //查询条件示例
//        //queryWrapper.eq(FileInfoEntity::getId, fileInfo.getId());
//        IPage<FileInfoEntity> iPage = this.page(pagePlug, queryWrapper);
//
//        IPage<FileInfoVO> iPageVO = new Page<>();
//        BeanUtils.copyProperties(iPage, iPageVO);
//
//        List<FileInfoVO> listVO = new ArrayList<>();
//        // 转换使用字典的属性
//        if (CollUtil.isNotEmpty(iPage.getRecords())) {
//            iPage.getRecords().forEach(item -> {
//                FileInfoVO vo = new FileInfoVO();
//                BeanUtils.copyProperties(item, vo);
//                // 需要转换的具体字典属性
//                listVO.add(vo);
//            });
//        }
//        iPageVO.setRecords(listVO);
//
//        return DataResult.success(iPageVO);
//    }



//    @Override
//    public void downloadZip(HttpServletResponse response, DownloadZipDTO dto) {
//        List<FileInfoEntity> datas =this.listByIds(dto.getIds());
//        String projectId = dto.getBusinessId();
//        // 所有文件夹
//        List<FileInfoEntity> dirList = datas.stream()
//                .filter(file -> "0".equals(file.getIsFile())).collect(Collectors.toList());
//        // 所有文件
//        List<FileInfoEntity> fileList = datas.stream()
//                .filter(file -> "1".equals(file.getIsFile())).collect(Collectors.toList());
//
//        if (CollUtil.isNotEmpty(dirList)){
//
//        }
////        List<FileInfoEntity> all = fileInfoRepository.findAll(specification);
////        fileList.addAll(all);
////        ZipUtils.createZipAndReturnPath(response, fileList,fastFileStorageClient);
//    }

    @Override
    public DataResult findByFileById(String id) {
        LambdaQueryWrapper<FileInfoEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FileInfoEntity::getBusinessId, id);
       List<FileInfoEntity> fileLis = this.list(queryWrapper);
        return DataResult.success(fileLis);
    }
}